package p12;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class P12Util {

    public  static PrivateKey getPrivateKey(){
        PrivateKey key = null;
        try {
            char[] password = "123456".toCharArray(); // 更改为你的keystore密码
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream fis = new FileInputStream("C:\\Users\\huangjian01\\Desktop\\keystore.p12"); // 更改为你p12文件的路径
            keyStore.load(fis, password);
            fis.close();
            String alias = keyStore.aliases().nextElement(); // 假设只有一个条目
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password);
            key = privateKey;
        } catch (Exception e) {

        }
        return key;
    }


    public  static PublicKey getPublicKey(){
        PublicKey key = null;
        try {
            // 加载KeyStore
            char[] password = "123456".toCharArray(); // 更改为你的keystore密码
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream fis = new FileInputStream("C:\\Users\\huangjian01\\Desktop\\keystore.p12"); // 更改为你p12文件的路径
            keyStore.load(fis, password);
            fis.close();
            String alias = keyStore.aliases().nextElement(); // 假设只有一个条目
            Certificate cert = keyStore.getCertificate(alias);
            PublicKey publicKey = cert.getPublicKey();
            key = publicKey;
        } catch (Exception e) {

        }
        return key;
    }


    public static Certificate getCertificate(){
        Certificate cert = null;
        try {
            char[] password = "123456".toCharArray(); // 更改为你的keystore密码
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream fis = new FileInputStream("C:\\Users\\huangjian01\\Desktop\\keystore.p12"); // 更改为你p12文件的路径
            keyStore.load(fis, password);
            fis.close();
            String alias = keyStore.aliases().nextElement(); // 假设只有一个条目
            cert = keyStore.getCertificate(alias);
        } catch (Exception e) {

        }
        return cert;
    }



}
